<template>
  <div class="bigbox">
    <van-nav-bar
      title="购物车"
      @click-left="$router.push('/home')"
      @click-right="delAll"
    >
      <template #left>
        <van-icon name="arrow-left" size="20" color="black" />
        返回
      </template>
      <template #right>
        <van-icon size="20" color="black" />
        清空购物车
      </template>
    </van-nav-bar>
    <div class="main">
      <div class="nothing" v-if="flag">
        <van-empty
          class="custom-image"
          image="https://img11.360buyimg.com/jdphoto/s180x180_jfs/t18163/292/540553659/74408/adeb7463/5a93c51cN3bb5e37b.png"
          description="空空如也"
        />
      </div>
      <div class="thing" v-else>
        <van-swipe-cell
          v-for="(item, index) in cartList"
          :key="index"
          :name="item.cartid"
          :before-close="beforeClose"
        >
          <van-checkbox
            v-model="item.flag"
            checked-color="#ee0a24"
            @click="seletone(item.cartid, item.flag)"
          ></van-checkbox>
          <van-card
            :price="item.originprice"
            :title="item.proname"
            :thumb="item.img1"
          >
            <template #num>
              <van-stepper
                v-model="item.num"
                @change="cartnumchange(item.cartid, item.num)"
              />
            </template>
          </van-card>
          <template #right>
            <van-button square type="danger" text="删除" class="delete" />
          </template>
        </van-swipe-cell>

        <div class="none"></div>

        <van-submit-bar
          :price="price*100"
          button-text="去结算"
          class="sub"
          @submit="onSubmit"
        >
          <van-checkbox
            v-model="isAll"
            class="box"
            checked-color="#ee0a24"
          ></van-checkbox>
        </van-submit-bar>
      </div>

      <van-divider
        :style="{
          color: '#ccc',
          borderColor: '#ccc',
          padding: '0 16px',
        }"
      >
        猜你喜欢
      </van-divider>
      <ul class="goods1">
        <li
          class="van-hairline--surround"
          v-for="(item, index) in recommendlist"
          :key="index"
          @click="jumpTo(item.proid)"
        >
          <img :src="item.img1" alt="" />
          <div>
            <h4 class="van-multi-ellipsis--l2">{{ item.proname }}</h4>
            <p class="money">￥{{ item.originprice }}</p>
            <!-- {{list}} -->
          </div>
        </li>
      </ul>
      
    </div>
  </div>
</template>

<script>
import Vue from "vue";
import {
  Empty,
  Card,
  Stepper,
  SwipeCell,
  Checkbox,
  CheckboxGroup,
  Dialog,
  SubmitBar,
  Divider,
  Toast,
} from "vant";
Vue.use(Empty);
Vue.use(Card);
Vue.use(Stepper);
Vue.use(SwipeCell);
Vue.use(Checkbox);
Vue.use(CheckboxGroup);
Vue.use(SubmitBar);
Vue.use(Divider);
Vue.use(Toast);
import {
  Cart,
  CartNum,
  CartRemove,
  CartSelectAll,
  CartSelectOne,
  RecommendList,
  addOrder,
  removeAll,
} from "../api/cart";
export default {
  data() {
    return {
      flag: null,
      cartList: [],
      recommendlist: [],
      time: null,
    };
  },
  created() {
    if (localStorage.getItem("token")) {
      //判断是否登陆
      this.getCartList(); //登录调用请求
    } else {
      this.$router.push("/login"); //没有登陆跳转至登录页
    }
    RecommendList().then((data) => {
      console.log(data);
      this.recommendlist = data.data.data;
    });
  },
  computed: {
    isAll: {
      //get决定当上面的flag全部为true，则isAll为true
      set(val) {
        // console.log(val);
        this.cartList.forEach((item) => {
          item.flag = val;
        });
        CartSelectAll({
          userid: localStorage.getItem("userid"),
          type: val,
        }).then((data) => {
          console.log(data);
          // this.getCartList();
        });
      },
      get() {
        return this.cartList.every((item) => {
          return item.flag == true;
        });
      },
    },
    price() {
      let newList = this.cartList.filter((item) => {
        return item.flag == true;
      });

      return newList.reduce((sum, item) => {
        return (sum = sum + ((item.originprice / 1) * item.num) / 1) ;
      }, 0);
    },
  },
  methods: {
    //不但可以写事件处理函数还可以写方法
    cartnumchange(cartid, num) {
      CartNum({ cartid: cartid, num: num }).then((data) => {
        console.log(data, num);
      });
    },
    getCartList() {
      //方法   数量和删除的数据变了以后要重新刷新渲染
      Cart({ userid: localStorage.getItem("userid") }).then((data) => {
        console.log(data.data.data);
        if (data.data.code == 10020) {
          this.flag = true;
        } else if (data.data.code == 200) {
          this.flag = false;
          this.cartList = data.data.data;
          console.log(this.cartList);
        }
      });
    },
    beforeClose({ name, position, instance }) {
      switch (position) {
        case "right":
          Dialog.confirm({
            //这是一个vant组件
            message: "确定删除吗？",
          })
            .then(() => {
              //在弹出框中，点击确定，就会执行此处的代码
              // console.log("确定");
              CartRemove({ cartid: name }).then((data) => {
                //删除单条数据接口，需要传参cartid，name是before-close上的参数，唯一标识，给他动态赋值item.cartid，在这得到的就是cartid
                console.log(data);
                if (data.data.code == "200") {
                  this.getCartList();
                }
              });
              instance.close();
            })
            .catch(() => {
              // 点击取消就会执行此处的代码
              // console.log("取消");
              instance.close();
            });
          break;
      }
    },
    seletone(cartid, flag) {
      CartSelectOne({ cartid: cartid, flag: flag }).then((data) => {
        console.log(data);
      });
    },
    jumpTo(proid) {
      this.$router.push("/detail/" + proid);
    },
    onSubmit() {
      //添加订单，先判断是否选中，选中后才能提交
      this.cartList.forEach((item) => {
        if (item.flag == true) {
          addOrder({
            //添加订单
            token: localStorage.getItem("token"),
            userid: localStorage.getItem("userid"),
          }).then((data) => {
            console.log(data);
            this.time = data.data.time;
          });
          setTimeout(() => {
            this.$router.push("/order/" + this.time);
          }, 1000);
        }
      });
    },
    delAll() {
      removeAll({
        token: localStorage.getItem("token"),
        userid: localStorage.getItem("userid"),
      }).then((data) => {
        console.log(data);
        this.time = data.data.time;
      });
      this.getCartList();
    },
  },
  name: "Cart",
  components: {},
};
</script>

<style scoped>
.delete {
  height: 100%;
}
::v-deep .van-swipe-cell__wrapper {
  /* ::v-deep  这几个类名在vscode是没写的，直接在浏览器里找到内置样式进行更改，就得用到::v-deep */
  display: flex;
  background-color: #fafafa;
  flex-wrap: wrap;
}
::v-deep .van-checkbox {
  width: 0.3rem;
  padding-left: 0.1rem;
}
::v-deep .van-card {
  flex: 1;
}
.sub {
  bottom: 0.44rem;
}
.goods1 {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  /* position: relative; */
}
.goods1 li {
  width: 48%;
}
.goods1 li img {
  width: 100%;
}
.none {
  height: 44px;
}
.custom-image .van-empty__image {
  width: 90px;
  height: 90px;
}
</style>